package com.glSto.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.glSto.domain.*;
import com.glSto.rep.POResponse;
import com.glSto.req.BomRequest;
import com.glSto.req.BomSendRequest;
import com.glSto.req.GoodsIssueRequest;
import com.glSto.req.PurchaseRequest;
import com.glSto.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("api/Power.GULEISTO/GULEISTO")
public class MdmController {

    // 为每个接口创建专门的日志记录器
    private static final Logger mainDataLogger = LoggerFactory.getLogger("com.glSto.controller.MdmController.mainData");
    private static final Logger bomRequestLogger = LoggerFactory.getLogger("com.glSto.controller.MdmController.bomRequest");
    private static final Logger poCallbackLogger = LoggerFactory.getLogger("com.glSto.controller.MdmController.poCallback");
    private static final Logger purchaseDataLogger = LoggerFactory.getLogger("com.glSto.controller.MdmController.purchaseData");
    private static final Logger goodsIssueLogger = LoggerFactory.getLogger("com.glSto.controller.MdmController.goodsIssue");

    @Autowired
    private MdmService mdmService;

    @Autowired
    private BomService bomService;

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private GoodsIssueService goodsIssueService;

    @Value("${mdm.tBasicAuth.username}")
    private String userName;

    @Value("${mdm.tBasicAuth.password}")
    private String passWord;
    /**
     * 获取主数据
     */
    @GetMapping("/api/erp/material")
    public ResultResponse getMainData() {
        mainDataLogger.info("进入获取主数据接口");
        ResultResponse response = new ResultResponse();

        try {
            String msg = mdmService.getMainData(userName, passWord);
            response.setCode(200);
            response.setSuccess(true);
            response.setMsg(msg);
            return response;
        } catch (Exception e) {
            mainDataLogger.error("获取主数据异常", e);
            response.setCode(500);
            response.setSuccess(false);
            response.setMsg("获取主数据失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 向BOM发送请求
     */
    @PostMapping("/api/bom/request")
    public ResultResponse requestBomData(@RequestBody BomRequest request) {
        bomRequestLogger.info("向BOM发送请求: {}", request);

        ResultResponse response = new ResultResponse();

        try {
            int result = bomService.getBOMData(request);

            if (result == 1) {
                bomRequestLogger.info("向BOM发送请求成功，等待对方平台回调");
                response.setCode(200);
                response.setSuccess(true);
                response.setMsg("BOM请求成功，等待数据回调");
                return response;
            } else {
                bomRequestLogger.error("向BOM发送请求失败");
                response.setCode(500);
                response.setSuccess(false);
                response.setMsg("BOM请求失败");
                return response;
            }
        } catch (Exception e) {
            bomRequestLogger.error("处理BOM请求时发生异常: ", e);
            response.setCode(500);
            response.setSuccess(false);
            response.setMsg("处理BOM请求时发生异常: " + e.getMessage());
            return response;
        }
    }


    /**
     * 接收对方平台发送数据（PO接口）
     */
    @PostMapping("/ERP_BOM")
    public ResultResponse receiveBomCallbackData(@RequestBody String requestBody) throws JsonProcessingException {
        poCallbackLogger.info("开始接收对方平台发送的BOM回调数据");
        poCallbackLogger.info("接收到对方平台发送的BOM回调数据: {}", requestBody);
        ObjectMapper mapper = new ObjectMapper();
        POResponse poResponse = mapper.readValue(requestBody, POResponse.class);
        System.out.println("解析后数据：" + poResponse);

        // 先处理数据
        if (poResponse != null && poResponse.getET_DATA() != null && !poResponse.getET_DATA().isEmpty()) {
            try {
                // 处理数据逻辑
                List<BomSendRequest> processedRequests = processBomData(poResponse);

                // 发送到外部接口
                if (processedRequests != null && !processedRequests.isEmpty()) {
                    String result = bomService.sendBomData(processedRequests);
                    poCallbackLogger.info("BOM数据发送结果: {}", result);

                    // 返回成功响应
                    ResultResponse successResult = new ResultResponse();
                    successResult.setCode(200);
                    successResult.setSuccess(true);
                    successResult.setMsg("数据处理成功");
                    successResult.setData(result);
                    return successResult;
                }
            } catch (Exception e) {
                poCallbackLogger.error("处理BOM数据时发生异常: ", e);
                ResultResponse errorResult = new ResultResponse();
                errorResult.setCode(500);
                errorResult.setSuccess(false);
                errorResult.setMsg("处理数据时发生异常: " + e.getMessage());
                return errorResult;
            }
        }

        // 如果没有数据或处理失败，返回默认响应
        ResultResponse defaultResult = new ResultResponse();
        defaultResult.setCode(200);
        defaultResult.setSuccess(true);
        defaultResult.setMsg("无有效数据或处理完成");
        return defaultResult;
    }

    /**
     * 处理BOM数据
     *
     * @param poResponse 原始响应数据
     * @return 处理后的BOM请求列表
     */
    private List<BomSendRequest> processBomData(POResponse poResponse) {
        List<BomSendRequest> requests = new ArrayList<>();

        // 遍历所有ET_DATA数据
        for (POResponse.EtData etData : poResponse.getET_DATA()) {
            if (etData != null) {
                BomSendRequest request = new BomSendRequest();

                // 设置通用字段
                request.setDataType("STO_MDM_01");
                request.setAppKey("stoApply");
                request.setTimestamp("1750644948350");
                request.setAccessToken("5411706e6b4a662481bcbeed9f4aec60");
                request.setOperationType("CREATE");

                // 设置具体数据
                request.setData(new BomSendRequest.Data());
                request.getData().setMaterialCode(etData.getIDNRK());
                request.getData().setMaterialName(etData.getMAKTX());
                request.getData().setMaterialAddDesc(etData.getSTLAN());
                request.getData().setFuncLocation(etData.getTPLNR());
                request.getData().setComponentQua(etData.getMENGE());
                request.getData().setSourceBomId(etData.getTPLNR());
                request.getData().setOrderNum(1);
                request.getData().setRemark(etData.getEQKTX());
                request.getData().setSourceApiData(etData);

                requests.add(request);
            }
        }
        return requests;
    }

    /**
     * 获取采购数据
     */
    @PostMapping("/api/erp/goods/req/purchase")
    public ResultResponse getGoodsPurchaseData(@RequestBody PurchaseRequest request) {
        purchaseDataLogger.info("进入获取采购数据接口:{}", request);
        ResultResponse response = new ResultResponse();

        try {
            PurchaseResponse purchaseResponse = mdmService.getPurchaseData(request);
            response.setCode(200);
            response.setSuccess(true);
            response.setMsg("采购数据获取成功");
            response.setData(purchaseResponse);
            return response;
        } catch (Exception e) {
            purchaseDataLogger.error("获取采购数据异常", e);
            response.setCode(500);
            response.setSuccess(false);
            response.setMsg("获取采购数据失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 获取物资出库数据
     */
    @PostMapping("/api/erp/goods/req/out")
    public ResultResponse getGoodsIssueData(@RequestBody GoodsIssueRequest request) {
        goodsIssueLogger.info("进入获取物资出库数据接口:"+ request);
        ResultResponse response = new ResultResponse();

        try {
            GoodsIssueResponse goodsIssueResponse = mdmService.getGoodsIssueData(request);
            response.setCode(200);
            response.setSuccess(true);
            response.setMsg("物资出库数据获取成功");
            response.setData(goodsIssueResponse);
            return response;
        } catch (Exception e) {
            goodsIssueLogger.error("获取物资出库数据异常", e);
            response.setCode(500);
            response.setSuccess(false);
            response.setMsg("获取物资出库数据失败: " + e.getMessage());
            return response;
        }
    }


    /**
     * 接收对方平台发送采购数据
     */
    @PostMapping("/api/erp/goods/purchase")
    public ResultResponse receivePurchaseData(@RequestBody String requestBody) {
        purchaseDataLogger.info("进入接收对方平台发送采购数据接口");
        purchaseDataLogger.info("接收对方平台发送的采购数据: {}", requestBody);

        ResultResponse response = new ResultResponse();

        try {
            String result = purchaseService.handlePurchaseData(requestBody);
            response.setCode(200);
            response.setSuccess(true);
            response.setMsg("采购数据处理成功");
            response.setData(result);
            return response;
        } catch (Exception e) {
            purchaseDataLogger.error("处理采购数据失败", e);
            response.setCode(500);
            response.setSuccess(false);
            response.setMsg("处理采购数据失败: " + e.getMessage());
            return response;
        }
    }


    /**
     * 获取物资出库数据
     */
    @PostMapping("/api/erp/goods/out")
    public ResultResponse receiveGoodsIssueData(@RequestBody String requestBody) {
        goodsIssueLogger.info("进入接收对方平台发送物资出库数据接口");
        goodsIssueLogger.info("接收对方平台发送的物资出库数据: {}", requestBody);

        ResultResponse response = new ResultResponse();

        try {
            String result = goodsIssueService.handleGoodsIssueData(requestBody);
            response.setCode(200);
            response.setSuccess(true);
            response.setMsg("物资出库数据处理成功");
            response.setData(result);
            return response;
        } catch (Exception e) {
            goodsIssueLogger.error("处理物资出库数据失败", e);
            response.setCode(500);
            response.setSuccess(false);
            response.setMsg("处理物资出库数据失败: " + e.getMessage());
            return response;
        }
    }
}
